package com.newviews.tcmip.web.controller;

import com.newviews.tcmip.common.config.ConfigProperties;
import com.newviews.tcmip.common.constant.CommonConsts;
import com.newviews.tcmip.common.model.PageModel;
import com.newviews.tcmip.common.model.ResultModel;
import com.newviews.tcmip.common.utils.*;
import com.newviews.tcmip.dao.EtcmPxExMapper;
import com.newviews.tcmip.pojo.po.EtcmUiElPo;
import com.newviews.tcmip.pojo.vo.EtcmCommonBaseInfoRespVO;
import com.newviews.tcmip.pojo.vo.export.*;
import com.newviews.tcmip.service.inf.EtcmDiseaseExServiceInf;
import com.newviews.tcmip.service.inf.EtcmPxServiceInf;
import com.newviews.tcmip.web.vo.combin.HerbHerbPageReqVo;
import com.newviews.tcmip.web.vo.combin.NetworkStatisticsRespVo;
import com.newviews.tcmip.web.vo.etcmpx.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 处方基本信息库 前端控制器
 * </p>
 *
 * @author lxc
 * @since 2024-02-29
 */
@RestController
@RequestMapping("/etcm/prescription")
@Api(tags = "处方信息")
@Slf4j
public class EtcmPxController {

    @Autowired
    private EtcmPxServiceInf etcmPxService;

    @Autowired
    private ConfigProperties configProperties;

    @Resource
    private EtcmPxExMapper etcmPxExMapper;
    @Resource
    private EtcmDiseaseExServiceInf etcmDiseaseExServiceInf;


    @GetMapping("/page")
    @ApiOperation("获取处方首页数据分页信息")
    public ResultModel<PageModel<Map<String,String>>>getPage(@RequestParam(required = false) String prescriptionType,
                                                             @RequestParam(required = false) String dosageForm,
                                                             @RequestParam(required = false) String content,
                                                             @RequestParam String langCode,
                                                             @RequestParam String uiTypeCode,
                                                             @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                             @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                             @RequestParam(required = false, defaultValue = "desc") String sortType){
        return etcmPxService.getPage(prescriptionType, dosageForm, content, langCode,uiTypeCode, pageNo, pageSize, sortType);
    }

    @GetMapping("/statistics")
    @ApiOperation("处方首页统计")
    public ResultModel<EtcmStatisticsRespVo>statisticsPx(@RequestParam(required = false) String content){
        return etcmPxService.statisticsPx(content);
    }
    @PostMapping("/download")
    @ApiOperation(value = "处方数据首页信息下载")
    public void downloadTarget(
            @ApiIgnore HttpServletResponse response,
            @RequestBody @Valid EtcmPxExportReqVO reqVO)
    {
        try {
            List<Map<String, String>> pxList = etcmPxService.getPxDownload(reqVO.getPrescriptionType(), reqVO.getDosageForm(), reqVO.getContent(), reqVO.getLangCode(), reqVO.getUiTypeCode(),reqVO.getSortType());
            etcmDiseaseExServiceInf.getDownload(response,reqVO.getUiTypeCode(),reqVO.getLangCode(),reqVO.getExportType(),pxList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/details")
    @ApiOperation("获取处方基本信息分页信息")
    public ResultModel<List<EtcmCommonBaseInfoRespVO>>getDetails(@RequestParam String prescriptionId,
                                                                     @RequestParam String langCode,
                                                                     @RequestParam String uiTypeCode,
                                                                     @RequestParam String content){
        return etcmPxService.getDetails(prescriptionId, langCode, uiTypeCode, content);
    }
    @PostMapping("/details/download")
    @ApiOperation(value = "处方数据详情信息下载")
    public void downloadDetails(
            @ApiIgnore HttpServletResponse response,
            @RequestBody @Valid EtcmPxDetailsExportReqVO reqVO) {
        String path="";
        try {
            String filename = "";
            List<Map<String, String>> pxList = etcmPxService.getPxDetails(reqVO.getPxId(), reqVO.getContent(), reqVO.getLangCode(), reqVO.getUiTypeCode());
            File file=new File(configProperties.getFileExportPath());
            if(!file.exists()){
                file.mkdirs();
            }
            if(reqVO.getExportType().equals(CommonConsts.STR_COMMON_YES)){
                filename = UUIDGenerator.getDateNumber()+CommonConsts.EXPORT_FILE_FORMAT_1;
                path= configProperties.getFileExportPath()+ filename;
                ExportExcelUtils.writeListOfMapsToCSV(pxList, path);
            }else {
                filename = UUIDGenerator.getDateNumber()+CommonConsts.EXPORT_FILE_FORMAT_2;
                path= configProperties.getFileExportPath()+ filename;
                ExportExcelUtils.writeListOfMapsToTxt(pxList, path);
            }
            InputStream stream = new FileInputStream(path);
            response.setHeader("Content-Disposition", "attachment;"+"filename=" + new String(filename.getBytes(), "utf-8"));
            ServletOutputStream out = response.getOutputStream();
            byte buff[] = new byte[1024];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            stream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            new File(path).delete();
        }
    }




    @GetMapping("/ingredient")
    @ApiOperation("获取草药成分信息")
    public ResultModel<PageModel<Map<String,String>>> getIngredient(@RequestParam(required = false) String ingrHia,
                                                                    @RequestParam(required = false) String ingrBbb,
                                                                    @RequestParam(required = false) String ingrCaco2,
                                                                    @RequestParam(required = false) String ingrHob,
                                                                    @RequestParam(required = false) String content,
                                                                    @RequestParam String langCode,
                                                                    @RequestParam String uiTypeCode,
                                                                    @RequestParam String prescriptionId,
                                                                    @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                                    @RequestParam(required = false, defaultValue = "desc") String sortType){

        return etcmPxService.getIngredient(ingrHia, ingrBbb, ingrCaco2,ingrHob,content, langCode, uiTypeCode, prescriptionId, pageNo, pageSize, sortType);
    }

    @GetMapping("/statistics/ingredient")
    @ApiOperation("处方成分统计")
    public ResultModel<PxIngrStatisticsRespVo> getIngredientStatistics(@RequestParam(required = false) String content,
                                                                       @RequestParam String prescriptionId){

        return etcmPxService.getIngredientStatistics(content, prescriptionId);
    }

    @PostMapping("/download/ingredient")
    @ApiOperation(value = "处方成分下载")
    public void downloadIngredient(
            @ApiIgnore HttpServletResponse response,
            @RequestBody @Valid PxIngrDownLoadRespVo reqVO) {

        try {
            List<Map<String, String>> list = etcmPxService.getIngredientDownload(reqVO.getIngrHia(), reqVO.getIngrBbb(), reqVO.getIngrCaco2(),reqVO.getIngrHob(),reqVO.getContent(), reqVO.getLangCode(), reqVO.getUiTypeCode(), reqVO.getPrescriptionId(), reqVO.getSortType());
            etcmDiseaseExServiceInf.getDownload(response,CommonConsts.UI_TYPE_CODE_PX_INGR,reqVO.getLangCode(),reqVO.getExportType(),list);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @GetMapping("/target")
    @ApiOperation("获取成分靶向信息")
    public ResultModel<PageModel<Map<String,String>>> getTarget(@RequestParam(required = false) String targetType,
                                                                @RequestParam(required = false) String content,
                                                                    @RequestParam String langCode,
                                                                    @RequestParam String uiTypeCode,
                                                                    @RequestParam String prescriptionId,
                                                                    @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                                    @RequestParam(required = false, defaultValue = "desc") String sortType){

        return etcmPxService.getTarget(targetType,content, langCode, uiTypeCode, prescriptionId, pageNo, pageSize, sortType);
    }

    @GetMapping("/target/statistics")
    @ApiOperation("获取成分靶向统计")
    public ResultModel<Map<String,String>> getTargetStatistics(@RequestParam(required = false) String content,
                                                                @RequestParam String prescriptionId){

        return etcmPxService.getTargetStatistics(content, prescriptionId);
    }

    @PostMapping("/download/target")
    @ApiOperation(value = "处方靶向下载")
    public void downloadTarget(
            @ApiIgnore HttpServletResponse response,
            @RequestBody @Valid PxTargetDownLoadRespVo reqVO) {
        try {
            List<Map<String, String>> list = etcmPxService.getTargetDownload(reqVO.getType(),reqVO.getContent(), reqVO.getLangCode(), reqVO.getUiTypeCode(), reqVO.getPrescriptionId(), reqVO.getSortType());
            etcmDiseaseExServiceInf.getDownload(response,reqVO.getUiTypeCode(),reqVO.getLangCode(),reqVO.getExportType(),list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    @GetMapping("/experimental")
    @ApiOperation("获取处方组学信息")
    public ResultModel<PageModel<Map<String,String>>> getExperimental(@RequestParam(required = false) String content,
                                                                    @RequestParam String prescriptionId,
                                                                    @RequestParam String langCode,
                                                                    @RequestParam String uiTypeCode,
                                                                    @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                                    @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                                    @RequestParam(required = false, defaultValue = "desc") String sortType){
        return etcmPxService.getExperimental(content, prescriptionId, langCode, uiTypeCode, pageNo, pageSize,sortType);
    }

    @PostMapping("/download/experimental")
    @ApiOperation("下载处方组学信息")
    public void downloadExperimental(
            @ApiIgnore HttpServletResponse response,
            @RequestBody @Valid EtcmPxExperimentExportReqVO reqVO) {
        try {
            List<Map<String, String>> list = etcmPxService.getExperimentalList(reqVO.getContent(), reqVO.getPxId(),reqVO.getLangCode(),reqVO.getUiTypeCode(),reqVO.getSortType());
            etcmDiseaseExServiceInf.getDownload(response,reqVO.getUiTypeCode(),reqVO.getLangCode(),reqVO.getExportType(),list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    @GetMapping("/network/statistics")
    @ApiOperation("处方network图")
    public ResultModel<NetworkStatisticsRespVo>networkStatistics(@RequestParam String prescriptionId, @RequestParam String uiTypeCode, @RequestParam String langCode){
        return etcmPxService.networkStatistics(prescriptionId,langCode,uiTypeCode);
    }

    @GetMapping("/network/thermal/statistics")
    @ApiOperation("处方热力图")
    public ResultModel<NetworkStatisticsRespVo>networkThermalStatistics(@RequestParam String prescriptionId, @RequestParam String uiTypeCode, @RequestParam String langCode){
        return etcmPxService.networkStatistics(prescriptionId,langCode,uiTypeCode);
    }

    @GetMapping("/network/page")
    @ApiOperation("处方network table")
    public ResultModel<PageModel<Map<String,String>>>networkPage(@RequestParam String prescriptionId, @RequestParam String uiTypeCode, @RequestParam String langCode,@RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                                 @RequestParam(required = false, defaultValue = "10") Integer pageSize){
        return etcmPxService.networkPage(prescriptionId,langCode,uiTypeCode,pageNo,pageSize);
    }
    @PostMapping("/network/download")
    @ApiOperation("处方network图下载")
    public void networkStatistics( @ApiIgnore HttpServletResponse response,@RequestBody EtcmPxNetworkExportReqVO reqVO){
        try {
            ResultModel<PageModel<Map<String, String>>> res = etcmPxService.networkPage( reqVO.getPrescriptionId(),reqVO.getLangCode(),reqVO.getUiTypeCode(), 1,200);
            if (!res.isSuccess()){
                log.error(res.getMessage());
                return;
            }

            etcmDiseaseExServiceInf.getDownload(response,reqVO.getUiTypeCode(),reqVO.getLangCode(),reqVO.getExportType(),res.getData().getRecords());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }




}
